package com.example.blockingqueue.blockingqueueconfig.linkedqueue;

import com.example.blockingqueue.controller.Order;
import com.example.blockingqueue.controller.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.util.concurrent.LinkedBlockingQueue;

/*ApplicationRunner的作用--项目启动后就执行run方法*/
@Component
public class LinkedBlockingQueueConsumer implements ApplicationRunner {

    @Autowired
    @Qualifier("linkedQueue4Order")
    private LinkedBlockingQueue<Order> linkedQueue4Order;

    @Autowired
    @Qualifier("linkedQueue4Task")
    private LinkedBlockingQueue<Task> linkedQueue4Task;

    @Override
    public void run(ApplicationArguments args) {
        /*开启一个线程 去监听 linkedBlockingQueue*/
        new Thread(() -> {
            while (true) {
                try {
                    Order order = linkedQueue4Order.take();
                    order.run();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();

        new Thread(() -> {
            while (true) {
                try {
                    Task task = linkedQueue4Task.take();
                    task.run();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();


    }
}
